package csnet.openflow.component.receiver;

import java.io.IOException;

import csnet.openflow.component.Device;
import csnet.openflow.component.link.Link;
import csnet.openflow.packet.model.Packet;
import csnet.openflow.util.fileOperation.StreamWriter;
import csnet.openflow.util.log.LoggerGenerator;

public class Receiver implements Device {
    private Link input;
    private StreamWriter writer;

    @Override
    public boolean schedule(long timestamp) {
        input.setCurrentTime(timestamp);
        Packet packet = null;
        int num = 0;
        while ((packet = input.receive()) != null) {
            ++num;
            recordPacket(packet);
        }
        return (num > 0);
    }

    public void setLogger(LoggerGenerator logger) {
        writer = logger.getBinaryLogger("receiver");
    }

    public void connect(Link input) {
        this.input = input;
    }

    private void recordPacket(Packet packet) {
        try {
            writer.writeLong(packet.statistic.packetIndex);
            writer.writeLong(packet.statistic.flowIndex);
            writer.writeLong(packet.getTimestamp());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
